#define _CRT_SECURE_NO_WARNINGS
#include "SList.h"


void SListPrint(STLNode* phead)
{
	STLNode* cur = phead;
	while (cur->next != NULL)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

SListNode* BuySListNode(SLTDataType x)
{
	STLNode* newnode = (STLNode*)malloc(sizeof(STLNode));
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}
void SListPushBack(STLNode** pphead,SLTDataType x)
{
	STLNode* newnode = BuySListNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		STLNode* tail = *pphead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}
void SListPushFront(STLNode** pphead, SLTDataType x)
{
	STLNode* newnode = BuySListNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}
void SListPopFront(STLNode** pphead)
{
	STLNode* next = (*pphead)->next;
	free(*pphead);
	* pphead = next;
}
void SListPopBack(STLNode** pphead)
{
	if (*pphead == NULL)
	{
		return;
	}
	else if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SListNode* prev = *pphead;
		SListNode* tail = *pphead;
		while (tail->next != NULL)
		{
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		prev->next = NULL;
	}
}
STLNode* SListFind(STLNode* phead, SLTDataType x)
{
	STLNode* cur = phead;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
			cur = cur->next;
	}
	return NULL;
}
void SListInsert(STLNode** pphead, STLNode* pos, SLTDataType x)
{
	if (*pphead == pos)
	{
		SListPushFront(pphead,x);
	}
	else
	{
		STLNode* newnode = BuySListNode(x);
		STLNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = newnode;
		newnode->next = pos;
		
	}
}
void SListErase(STLNode** pphead, STLNode* pos)
{
	if (pos == *pphead)
	{
		SListPopFront(pphead);
	}
	else
	{
		STLNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
	}
}